package com.bitdf.txing.ware.listener;

import com.bitdf.txing.common.to.mq.OrderTo;
import com.bitdf.txing.common.to.mq.StockLockedTo;
import com.bitdf.txing.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Slf4j
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Autowired
    WareSkuService wareSkuService;

    /**
     * 30分钟后 检查订单 释放库存
     * @param to
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        try {
            wareSkuService.unlockStock(to);
            log.info("收到接收解锁库存的信息");
            //不批量处理
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            log.info("rabbitMQ错误"+e.getMessage());
            //将消息重新回队
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    /**
     * 超时未支付 自动关闭订单后 解锁库存
     * @param orderTo
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo orderTo, Message message, Channel channel) throws IOException {
        try {
            log.info("订单关闭，准备解锁库存");
            wareSkuService.unlockStock(orderTo);
            //不批量处理
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            log.info("rabbitMQ错误"+e.getMessage());
            //将消息重新回队
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
